package com.zqu.ordersystem.service.impl;

import com.zqu.ordersystem.service.FileUploadService;
import com.zqu.ordersystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Autowired
    private UserService userService;

    @Override
    public String uploadAvatar(Integer userId, MultipartFile file) {
        try {
            System.out.println("开始处理头像上传，用户ID: " + userId);
            System.out.println("配置的上传目录: " + uploadDir);

            // 检查文件是否为空
            if (file.isEmpty()) {
                throw new RuntimeException("上传文件为空");
            }

            // 检查上传目录权限
            Path basePath = Paths.get("").toAbsolutePath().resolve(uploadDir);
            System.out.println("解析后的绝对路径: " + basePath);

            if (!Files.exists(basePath)) {
                System.out.println("目录不存在，尝试创建...");
                Files.createDirectories(basePath);
            }
            if (!Files.isWritable(basePath)) {
                throw new RuntimeException("上传目录不可写: " + basePath +
                    " 请检查目录权限或手动创建目录");
            }
            Path uploadPath = basePath.resolve("avatars");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = "avatar_" + userId + "_" + UUID.randomUUID() + fileExtension;

            // 保存文件
            Path filePath = uploadPath.resolve(newFilename);
            file.transferTo(filePath.toFile());

            // 返回相对URL路径
            String avatarUrl = "/uploads/avatars/" + newFilename;
            return userService.updateUserAvatar(userId, avatarUrl);
        } catch (IOException e) {
            System.err.println("头像上传失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("头像上传失败: " + e.getMessage(), e);
        }
    }
    @Override
    public String uploadDishImage(Integer dishId, MultipartFile file) {
        try {
            System.out.println("开始处理食品图片上传，菜品ID: " + dishId);
            System.out.println("配置的上传目录: " + uploadDir);

            // 确保上传目录存在
            Path uploadPath = Paths.get("").toAbsolutePath().resolve(uploadDir + "/dishes");
            System.out.println("食品图片上传路径: " + uploadPath);

            if (!Files.exists(uploadPath)) {
                System.out.println("目录不存在，尝试创建...");
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = "dish_" + dishId + "_" + UUID.randomUUID() + fileExtension;

            // 保存文件
            Path filePath = uploadPath.resolve(newFilename);
            file.transferTo(filePath.toFile());

            // 返回相对URL路径
            return "/uploads/dishes/" + newFilename;
        } catch (IOException e) {
            System.err.println("食品图片上传失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("食品图片上传失败: " + e.getMessage(), e);
        }
    }
}
